package com.katsu.myapplib.secret;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class SecretAESDESede implements Secret<String, String> {

    public static final String DESEDE_CBC_PKCS5PADDING = "DESede/CBC/PKCS5Padding";

    public static final String DESEDE_CBC_PKCS7PADDING = "DESede/CBC/PKCS7Padding";

    public static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";

    public static final String AES_CBC_PKCS7PADDING = "AES/CBC/PKCS7Padding";

    public static final String DESEDE_CBC_NOPADDING = "DESede/CBC/NoPadding";

    private IvParameterSpec b;

    private SecretKeySpec c;

    private Cipher a;

    public SecretAESDESede(String md5, String cipherType) {

        this(md5.substring(0, 15), md5.substring(16, 31), cipherType);

    }

    public SecretAESDESede(String secretKey, String iv, String cipherType) {

        try {

            String f = cipherType.split("/")[0];

            a = Cipher.getInstance(cipherType);

            c = new SecretKeySpec(a(secretKey, f.equals("AES") ? 16 : 24), f);

            b = new IvParameterSpec(a(iv, f.equals("AES") ? 16 : 8));

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    @Override
    public String encrypt(String plaintext) throws Exception {

        a.init(Cipher.ENCRYPT_MODE, c, b);

        return new String(Base64.encode(a.doFinal(plaintext.getBytes()), Base64.DEFAULT));

    }

    @Override
    public String decrypt(String ciphertext) throws Exception {

        a.init(Cipher.DECRYPT_MODE, c, b);

        byte[] b = a.doFinal(Base64.decode(ciphertext.getBytes(), Base64.DEFAULT));

        return b != null ? new String(b) : ciphertext;

    }

    private byte[] a(String s, int z) {

        byte[] a = s.getBytes();

        byte[] b = new byte[z];

        for (int i = 0; i < a.length && i < b.length; ++i) {

            b[i] = a[i];

        }

        return b;

    }

}

